package mysql

import (
	"database/sql"
	"errors"
	"woanju/models"
)

func CheckEquipment(eid int64) error {
	sqlStr := `select count(user_id) from equipment where equipment_id=?`

	var count int
	err := db.Get(&count, sqlStr, eid)
	if err != nil {
		return err
	}

	if count > 0 {
		return ErrorEquipmentExist
	} else {
		return ErrorEquipmentNotExist
	}

}

func InsertEquipment(e *models.Equipment) error {
	sqlStr := `insert into equipment(equipment_id,user_id,equipment_name,status,type)values (?,?,?,?,?)`
	_, err := db.Exec(sqlStr, e.EquipmentID, e.UserID, e.EquipmentName, e.Status, e.Type)
	return err
}

func DeleteEquipment(eid int64) error {
	err := CheckEquipment(eid)
	if !errors.Is(err, ErrorEquipmentExist) {
		return err
	}
	sqlStr := `delete from equipment where equipment_id=?`
	_, err = db.Exec(sqlStr, eid)
	if err == sql.ErrNoRows {
		return ErrorEquipmentNotExist
	}
	return err
}

func GetEquipmentInfoByID(eid int64) (*models.Equipment, error) {
	e := new(models.Equipment)
	sqlStr := `select equipment_id,user_id,equipment_name,status,type from equipment where equipment_id=?`
	err := db.Get(e, sqlStr, eid)
	if err == sql.ErrNoRows {
		return nil, ErrorEquipmentNotExist
	}
	if err != nil {
		return nil, err
	}
	return e, nil
}

func UpdateEquipmentStatus(p *models.ParamEquipmentStatus) error {
	//1.拿到设备旧状态
	e, err := GetEquipmentInfoByID(p.EquipmentID)
	if err != nil {
		return err
	}
	//判断是否重复操作
	if p.Direction == e.Status {
		return ErrorRepeated
	}
	//更改设备状态
	sqlStr := `update equipment set status=? where equipment_id=?`
	_, err = db.Exec(sqlStr, p.Direction, p.EquipmentID)
	return err

}

func GetEquipmentListOrderOne(uid int64) ([]*models.Equipment, error) {
	data := make([]*models.Equipment, 0)
	sqlStr := `select equipment_id,user_id,equipment_name,status,type from equipment where user_id=? and type=1`
	err := db.Select(&data, sqlStr, uid)
	return data, err
}

func GetEquipmentListOrderTwo(uid int64) ([]*models.Equipment, error) {
	data := make([]*models.Equipment, 0)
	sqlStr := `select equipment_id,user_id,equipment_name,status,type from equipment where user_id=? and type=2`
	err := db.Select(&data, sqlStr, uid)
	return data, err
}
